#!/opt/local/bin/python

import sys, os
from stats import *
from datetime import datetime, timedelta
NoDataVal = -999.99

# check for proper number of command line arguments
if ( len( sys.argv ) != 3 ):
    sys.stderr.write( "\nUsage: %s <daily flow file> <output stat file>\n\n" % sys.argv[0] )
    sys.exit()
# handle command line arguments
InFile = sys.argv[1]
OutFile = sys.argv[2]
# open and read input file
if os.path.isfile( InFile ):
    # file found, so open and read contents
    fin = open( InFile, "r" )
    lines = fin.readlines()
    fin.close()
else:
    # file not available
    sys.stderr.write( "ERROR: Unable to find input file, %s.\n" % InFile )
    sys.exit()

print "Total number of days : %s" %len(lines)
# parse file data
for lidx in range(len(lines)):
    lines[lidx] = lines[lidx].strip().split("\t") # strip white space from start and end of line, and split on tab
    lines[lidx][0] = datetime.strptime( lines[lidx][0], "%Y/%m/%d"  ) # convert date to datetime element

# establish file start and end dates
FileStart = lines[0][0]
FileEnd   = lines[-1][0]

StartDate = FileStart
EndDate = FileEnd
StartYear = FileStart.year
EndYear = FileEnd.year
print  "The start year of the data is : %s" % StartYear
print  "The end year of the data is : %s" % EndYear


# prepare data array
NumYears = (EndYear - StartYear) + 1 # does not include final year
ObsValues = [0] * NumYears
NextDate = StartDate
for yidx in range(NumYears):
    LastDate = NextDate
    NextDate = datetime( NextDate.year+1, NextDate.month, NextDate.day )
    NumDays = (NextDate - LastDate).days
    ObsValues[yidx]=[-999.99]*NumDays


# parse file data
LastDayOfRange = datetime( EndDate.year+1, EndDate.month, EndDate.day )+timedelta(days=92) # we add 92 days to the start date because there are 92 days between October 1st and the end of the calendar year.
for lidx in range(len(lines)): #which is 817 for the first file
    dt = (lines[lidx][0])+timedelta(days=92)# we add 92 days to the start date because there are 92 days between October 1st and the end of the calendar year.
    if dt >= StartDate and dt < LastDayOfRange:
        yearIndex = dt.year-StartDate.year
        dayIndex = dt.toordinal() - (datetime(dt.year,10,1).toordinal())
        ObsValues[yearIndex][dayIndex]=float(lines[lidx][1])
        
#print ObsValues
fout = open( OutFile, "w" )
fout.write( "Year\tMean\tMax\tMin\tStdDev\tSum_over\tSum_under\n" )
for yidx in range( NumYears ):
    fout.write("%i" % (StartYear+yidx) ) # water years are numbered based on the year with more months
    MetricVal1 = get_mean( ObsValues[yidx], NoData=NoDataVal )
    fout.write("\t%f" % MetricVal1[0] ) 
    MetricVal = get_max( ObsValues[yidx], NoData=NoDataVal )
    fout.write("\t%f" % MetricVal[0] ) 
    MetricVal = get_min( ObsValues[yidx], NoData=NoDataVal )
    fout.write("\t%f" % MetricVal[0] ) 
    MetricVal2 = get_stdev( ObsValues[yidx], NoData=NoDataVal )
    fout.write("\t%f" % MetricVal2[0] ) 
    MetricVal = get_sum_over_threshold( ObsValues[yidx], MetricVal1[0] + MetricVal2[0]*1.5, NoData=NoDataVal )
    fout.write("\t%f" % MetricVal[0] ) 
    MetricVal = get_sum_under_threshold( ObsValues[yidx],MetricVal1[0] -MetricVal2[0]*1.5 , NoData=NoDataVal )
    fout.write("\t%f\n" % MetricVal[0] ) 


